import 'dart:async';

import 'package:adaptivex/adaptivex.dart';
import 'package:customer/constant/db_constant.dart';
import 'package:customer/db/entity/CustomerBillAttr.dart';
import 'package:customer/extension/extension_widget.dart';
import 'package:customer/theme.dart';
import 'package:customer/utils/snackbar.dart';
import 'package:fluent_ui/fluent_ui.dart' as fluent;
import 'package:flutter/material.dart';

import '../../constant/edit_constant.dart';
import '../../db/entity/CustomerBill.dart';
import '../../main.dart';
import '../../three/datatable/datatable_header.dart';
import '../../three/datatable/responsive_datatable.dart';
import '../../widgets/gyy_dialog.dart';
import '../../widgets/gyy_theme.dart';
import '../../widgets/page.dart';
import '../attribute/edit_attribute.dart';
import 'bill_edit.dart';
import 'bill_list_product.dart';

///客户订单列表

class BillListPage extends StatefulWidget {
  const BillListPage({Key? key}) : super(key: key);

  @override
  State<BillListPage> createState() => _EditAttributeState();
}

class _EditAttributeState extends State<BillListPage> with PageMixin {
  late List<DatatableHeader> _headers;

  var customerBillDao = database.customerBillDao;
  var customerBillAttrDao = database.customerBillAttrDao;
  List<CustomerBill> allList = [];

  //每页的数量 数组
  final List<int> _perPages = [10, 20, 50, 100];

  //每页的数量 当前的
  int _currentPerPage = 10;

  //当前页
  int _currentPage = 1;

  //搜索文字
  String searchText = '';

  int _total = 100;

  final List<Map<String, dynamic>> _sourceOriginal = [];
  List<Map<String, dynamic>> _sourceFiltered = [];
  List<Map<String, dynamic>> _pageList = []; //

  //选中的一级数据
  List<Map<String, dynamic>> _selectedList = [];
  int? selectId;

  //展开的一级属性
  Map<String, dynamic> expandedData = {};

  String? _sortColumn;
  final bool _sortAscending = true;
  bool _isLoading = true;
  late Timer delayedTimer;
  final String _searchKey1 = DbConstant.customer_name;
  final String _searchKey2 = DbConstant.customer_phone;

  //加载所有的
  loadAll() async {
    allList = await customerBillDao.findAll();
    setState(() {});
    _pullData();
  }

  //加载订单的扩展属性
  Future<List<CustomerBillAttr>> loadChildren(int billId) async {
    return await customerBillAttrDao.findByBillId(billId);
  }

  deleteOne(int id) async {
    //todo 删除订单相关的属性
    await customerBillDao.deleteById(id);
    await loadAll();
  }

//加载数据
  _pullData() async {
    setState(() => _isLoading = true);
    delayedTimer = Timer(delayedDuration, () {
      _sourceOriginal.clear();
      _sourceOriginal.addAll(_generateData());
      _sourceFiltered = _sourceOriginal;
      _total = _sourceFiltered.length;
      if (_currentPerPage > _sourceOriginal.length) {
        _pageList =
            _sourceFiltered.getRange(0, _sourceOriginal.length).toList();
      } else {
        _pageList = _sourceFiltered.getRange(0, _currentPerPage).toList();
      }
      setState(() => {_isLoading = false});
    });
  }

  //重置数据
  _resetData({start = 0}) async {
    setState(() => _isLoading = true);
    var _expandedLen =
        _total - start < _currentPerPage ? _total - start : _currentPerPage;
    Future.delayed(const Duration(seconds: 0)).then((value) {
      _pageList.clear();
      _pageList =
          _sourceFiltered.getRange(start, start + _expandedLen).toList();
      setState(() => _isLoading = false);
    });
  }

  //过滤数据
  _filterData(value) {
    setState(() => _isLoading = true);
    try {
      if (value == "" || value == null) {
        _sourceFiltered = _sourceOriginal;
      } else {
        _sourceFiltered = _sourceOriginal
            .where((data) =>
                data[_searchKey1]
                    .toString()
                    .toLowerCase()
                    .contains(value.toString().toLowerCase()) ||
                data[_searchKey2]
                    .toString()
                    .toLowerCase()
                    .contains(value.toString().toLowerCase()))
            .toList();
      }

      _total = _sourceFiltered.length;
      var _rangeTop = _total < _currentPerPage ? _total : _currentPerPage;
      _pageList = _sourceFiltered.getRange(0, _rangeTop).toList();
    } catch (e) {
      debugPrint(e.toString());
    }
    setState(() => _isLoading = false);
  }

  @override
  void initState() {
    super.initState();

    /// set headers
    _headers = _generateHeader();
    loadAll(); //加载所有产品
  }

  @override
  void dispose() {
    super.dispose();
    delayedTimer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            children: [
          Container(
            margin: const EdgeInsets.all(10),
            constraints: const BoxConstraints(
              maxHeight: 800,
            ),
            child: Card(
              child: ResponsiveDatatable(
                reponseScreenSizes: const [ScreenSize.xs],
                actions: generateActions(),
                headers: _headers,
                source: _pageList,
                selecteds: _selectedList,
                selectId: selectId,
                showSelect: true,
                autoHeight: false,
                expandedData: expandedData,
                //展开的对象
                sortAscending: _sortAscending,
                sortColumn: _sortColumn,
                isLoading: _isLoading,
                //下拉内容
                dropContainer: (data) {
                  return Container(
                    child: FutureBuilder<List<CustomerBillAttr>>(
                      future: loadChildren(data["id"]),
                      builder: (context, snapshot) {
                        if (snapshot.data == null || snapshot.data!.isEmpty) {
                          return sizeBox;
                        } else {
                          return fluent.Column(
                            children: [
                              ...buildSelectedProducts(snapshot.data!)
                            ],
                          );
                        }
                      },
                    ),
                  );
                },
                onDrop: (value, item) {
                  debugPrint("$value == $item ");
                  if (value!) {
                    //记录展开数据
                    expandedData = item;
                  } else {
                    expandedData = {};
                  }
                },
                onSelect: (value, item) {
                  debugPrint("$value == $item ");
                  if (value!) {
                    if (_selectedList.isNotEmpty) {
                      _selectedList = [];
                      selectId = null;
                    }
                    setState(() => {
                          _selectedList.add(item),
                          selectId = item['id'],
                        });
                  } else {
                    var index = _selectedList.indexOf(item);
                    if (index != -1) {
                      _selectedList.removeAt(index);
                    }
                    selectId = null;
                    setState(() => {});
                  }
                },
                footers: [
                  Container(
                    padding: paddingH15,
                    child: pageRow,
                  ),
                  //页数选择
                  fluent.ComboBox<int>(
                    isExpanded: false,
                    value: _currentPerPage,
                    items: _perPages.map((e) {
                      return fluent.ComboBoxItem(
                        child: Text(e.toString()),
                        value: e,
                      );
                    }).toList(),
                    onChanged: (value) {
                      setState(() {
                        _currentPerPage = value!;
                        _currentPage = 1;
                        _resetData();
                      });
                    },
                  ),
                  Container(
                    padding: paddingH15,
                    child: Text("$_currentPage - $_currentPerPage of $_total"),
                  ),
                  IconButton(
                    icon: backIcon,
                    onPressed: _currentPage == 1
                        ? null
                        : () {
                            _currentPage--;
                            var _nextSet = (_currentPage - 1) * _currentPerPage;
                            if (_nextSet < _currentPerPage) _nextSet = 0;
                            setState(() {
                              _resetData(start: _nextSet);
                            });
                          },
                  ),
                  IconButton(
                    icon: forwardIcon,
                    onPressed: _total - _currentPage * _currentPerPage <= 0
                        ? null
                        : () {
                            var _nextSet = _currentPage * _currentPerPage;
                            setState(() {
                              _currentPage++;
                              _resetData(start: _nextSet);
                            });
                          },
                  )
                ],
                //头部样式
                headerDecoration: BoxDecoration(
                    color: Colors.grey[400]!,
                    border: Border(
                        bottom:
                            BorderSide(color: AppTheme.accentColor, width: 1))),
                selectedDecoration: BoxDecoration(
                  border: Border(
                      bottom:
                          BorderSide(color: AppTheme.accentColor, width: 1)),
                  color: AppTheme.accentColor,
                ),
                headerTextStyle: whiteStyle,
                rowTextStyle: TextStyle(color: AppTheme.accentColor),
                selectedTextStyle: whiteStyle,
              ),
            ),
          ),
        ]));
  }

  //构建订单的产品
  List<Widget> buildSelectedProducts(List<CustomerBillAttr> customerBillAttrs) {
    List<Widget> widgets = [];
    //产品code -> 产品属性map
    Map<String, List<CustomerBillAttr>> productAttrMap = {};
    for (var element in customerBillAttrs) {
      if (!productAttrMap.containsKey(element.productCode)) {
        //productAttrMap 添加productCode
        productAttrMap[element.productCode] = [element];
      } else {
        //productAttrMap 取出productCode对应的map，添加数据
        productAttrMap[element.productCode]?.add(element);
      }
    }
    //循环每一个 产品-属性map
    productAttrMap.forEach((element, list) {
      fluent.debugPrint(element);
      fluent.debugPrint(list.toString());

      var billProductPage = BillProductDropPage(list);
      widgets.add(billProductPage);
    });

    return widgets;
  }

  ///构建操作栏
  generateActions() {
    return [
      sizeBoxH5,
      Expanded(
          child: fluent.TextBox(
        placeholder: 'Enter search',
        onSubmitted: (value) {
          _filterData(value);
        },
        onChanged: (value) {
          searchText = value;
        },
      )),
      TextButton(
        onPressed: () => {_filterData(searchText)},
        child: const Text("搜索").margin(const fluent.EdgeInsets.all(5)),
      ),
      sizeBoxH10,
      fluent.Button(
        child: const Text(StringConstant.edit),
        onPressed: () async {
          if (_selectedList.isEmpty || _selectedList.length != 1) {
            showMessage(context, "请选择一条数据，进行编辑");
            return;
          }
          Map<String, dynamic> map = _selectedList[0];
          var res = await showWidgetDialog(
              context,
              EditBillPage(map[DbConstant.id], map[DbConstant.customer_name],map[DbConstant.customer_phone]));
          fluent.debugPrint(res);
          if (DialogConstant.ok == res) {
            showMessage(context, StringConstant.saveSuccess);
            loadAll();
          }
        },
      ),
      sizeBoxH10,
      fluent.FilledButton(
          //自定义按钮的颜色
          style: fluent.ButtonStyle(
              backgroundColor: fluent.ButtonState.resolveWith(
            (states) => fluent.Colors.errorPrimaryColor,
          )),
          child: const Text('删除'),
          onPressed: () async {
            if (_selectedList.isEmpty) {
              showMessage(context, "请选择一条数据，进行编辑");
              return;
            }
            var id = _selectedList[0][DbConstant.id];
            String? res = await showContentDialog(context, '删除选中的数据？');
            fluent.debugPrint(res);
            if (DialogConstant.ok == res) {
              deleteOne(id);
            }
          }),
    ];
  }

  ///构建数据item
  List<Map<String, dynamic>> _generateData() {
    List<Map<String, dynamic>> temps = [];
    for (var data in allList) {
      temps.add({
        "id": data.id,
        "customerName": data.customerName,
        "customerPhone": data.customerPhone,
        "subtotalFee": data.subtotalFee,
        "discount": data.discount,
        "price": data.price,
        "billDeposit": data.billDeposit,
        "billBalance": data.billBalance,
      });
    }
    return temps;
  }
}

///构建头部
_generateHeader() {
  return [
    DatatableHeader(text: "name", value: "customerName", sortable: true),
    DatatableHeader(text: "phone", value: "customerPhone", sortable: true),
    DatatableHeader(
      text: "subtotalFee",
      value: "subtotalFee",
      sortable: true,
    ),
    DatatableHeader(
      text: "discount",
      value: "discount",
      sortable: false,
    ),
    DatatableHeader(
      text: "price",
      value: "price",
      sortable: false,
    ),
    DatatableHeader(
      text: "deposit",
      value: "billDeposit",
      sortable: false,
    ),
    DatatableHeader(
      text: "balance",
      value: "billBalance",
      sortable: false,
    )
  ];
}
